<?php

/**
 * 考场
 * @author yanghao <yh38615890@sina.cn>
 * @date 07-04-12
 * @copyright (c) gandianli
 */

namespace app\api\controller;

use app\api\Base;
use app\common\model\Examsession;
use app\common\model\Monitor;
use com\gdl\newagk\dataobject\adminpaper\AdminpaperDTO;
use com\gdl\newagk\dataobject\adminuser\UserDTO;
use com\gdl\newagk\dataobject\examination\FaceType;
use com\gdl\newagk\interfaces\AdminpaperServiceClient;
use com\gdl\newagk\interfaces\AdminUserServiceClient;
use think\Config;
use think\Db;
use think\exception\HttpException;
use com\gdl\newagk\dataobject\examination\ExaminationRequestDTO;
use com\gdl\newagk\dataobject\examination\ExaminationDTO;
use com\gdl\newagk\interfaces\ExaminationServiceClient;
use think\Exception;
date_default_timezone_set('PRC');//中华人民共和国时区

class AdminExamination extends Base
{

	//考场设置
    public function examSetting() {
		$data = $this->request->post();

		//$data = json_decode('{"starttime":"2018-05-08 00:00:00","title":"qqq","status":"1","qid":209,"exam_types":"0","eventid":"","num":"12","archiving":"1","random":{"verifAble":true,"verif":"","num":"4","types":["takPic","blink"]},"displayScore":"1","endtime":"2018-06-20 00:00:00","monitor":"0","pid":"4","is_exam":"","end":{"verifAble":false,"verif":"","num":0,"types":["blink","takPic"]},"start":{"verifAble":true,"verif":"","num":"3","types":["takPic","blink","shaHis"]}}',true);
		
		if(empty($data['title']) || empty($data['pid']) || empty($data['qid']) || empty($data['starttime']) || empty($data['endtime'])){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}
		$data['title'] = getStr($data['title']);
		/********稍微处理下 下面几个数据*
		$data['title'] =  getStr($this->request->param('title'), 'string');
		$data['pid'] = $this->request->param('pid/d');
		$data['qid'] = $this->request->param('qid/d');
		$data['eventid'] = $this->request->param('eventid/d');
		$data['num'] = $this->request->param('num/d');
		******/
		/********稍微处理下 下面几个数据 end*******/
		if(!empty($data['start'])){
				$data['start'] = json_encode($data['start']);
			}
			if(!empty($data['random'])){
				$data['random'] = json_encode($data['random']);
			}
			if(!empty($data['end'])){
				$data['end'] = json_encode($data['end']);
			}
        try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new ExaminationServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $data;

            $result = $api->settingAdd($engprojectDo);
//			var_dump( $data);
	//	var_dump( $result);exit;
			if($result->code){
				$data =  ['msg'=>'添加成功','code'=>'200','data'=>$result->data[0]];
			} else {
				$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
			}
        } catch (Exception $ex) {
            $data = ['msg'=>'添加失败','code'=>'400','data'=>[]];
        }
        return json_encode($data);
    }
	
	//统计考场数量
    public function numExam() {
		$reg = $this->request->param('reg') ? getStr($this->request->param('reg'), 'string') : '';
		if($reg==''){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}
        try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new ExaminationServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new ExaminationDTO();
            $engprojectDo->reg = $reg;
            $result = $api->numExam($engprojectDo);
			if($result->code){
				
				/**计算百分比**round*/
				$datas = $result->data[0];
				$statistic = ['total'=>$datas['totals'],'num'=>[$datas['start'],$datas['process'],$datas['end']],'pro'=>['start'=>0,'process'=>0,'end'=>0]];
				unset($datas['totals']);
				foreach($datas as $k=>$v){
					$statistic['pro'][$k] = round(($v/$statistic['total'])*100);
				}
				
				/**计算百分比 end***/
				
				$data =  ['msg'=>'成功','code'=>'200','data'=>$statistic];
			} else {
				$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
			}
        } catch (Exception $ex) {
            $data = ['msg'=>'失败','code'=>'400','data'=>[]];
        }
        return json_encode($data);
    }
	
	//考场列表
    public function examList() 
    {		
        $plaform = [];
        //$filename['userid'] = $this->request->param('userid') ? $this->request->param('userid') : '';
        $filename['plaform_id'] = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 1;
        $filename['page'] = $this->request->param('page') > 1 ? $this->request->param('page/d') : 1;
        $filename['pagesize'] = $this->request->param('pagesize') > 0 ? $this->request->param('pagesize/d') : 10;
        $filename['title'] = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : '';
        $filename['status'] = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';
        $filename['del'] = $this->request->param('del') ? getStr($this->request->param('del'), 'string') : '';
        /*         * *********** */
        $filename['monitorRule'] = $this->request->param('monitorRule') ? $this->request->param('monitorRule/d') : 0;
        $filename['isexam'] = $this->request->param('isexam')>-1 ? getStr($this->request->param('isexam'), 'int') : '';
        $filename['exam'] = $this->request->param('exam') ? getStr($this->request->param('exam'), 'string') : '';
        $filename['endtime'] = $this->request->param('endtime') ? $this->request->param('endtime') : '';
        $filename['startime'] = $this->request->param('startime') ? $this->request->param('startime') : '';
        /*         * *********** */
        if (!$filename['plaform_id']) {
            $data = ['msg' => '缺少参数', 'code' => '500'];
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk', 'gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;
            $result = $UserService->examList($engprojectDo);

            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg' => '查询成功', 'code' => '200'];
                    $plaform['data'] = $result->data;
                    $plaform['totalNumber'] = $result->message;
                } else {
                    $plaform = ['msg' => '查询失败', 'code' => '400'];
                    $plaform['data'] = [];
                    $plaform['totalNumber'] = 0;
                }
            } else {
                $plaform = ['msg' => '没有数据', 'code' => '400'];
                $plaform['data'] = [];
                $plaform['totalNumber'] = 0;
            }
        } catch (Exception $ex) {
            $data = ['msg' => '发生异常，查询失败', 'code' => '400', 'data' => []];
        }

        return json_encode($plaform);
    }

    //考场设置查询
    public function examSelect() {
		
        $plaform = [];
        $examid = $this->request->param('examid') ? $this->request->param('examid/d') : 0;
		$admin_reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		if(!$examid){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
            try {
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
                $UserService = new ExaminationServiceClient(NULL);
                \ApiClient::build($UserService);
				$engprojectDo = new ExaminationRequestDTO();
				$engprojectDo->id = $examid;
				$engprojectDo->username = $admin_reg;
                $result = $UserService->examSelect($engprojectDo);

                if ($result->success == TRUE) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'查询成功','code'=>'200'];
                        $plaform['data'] = json_decode($result->message,true);
                    } else {
						$plaform = ['msg'=>'查询失败','code'=>'400'];
                        $plaform['data'] = [];
                    }
                } else {
					$plaform = ['msg'=>'没有数据','code'=>'400'];
                    $plaform['data'] = [];
                    
                }
            } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
            }
           
            return json_encode($plaform);
    }
	
	//考场修改
    public function examEdit(){
		
        $plaform = [];
		$data = $this->request->post();
		$examid = !empty($data['examid']) ? intval($data['examid']) : 0;
		unset($data['examid']);
		if(!$examid || empty($data['title']) || empty($data['pid']) || empty($data['qid']) || empty($data['starttime']) || empty($data['endtime'])){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}
		/********稍微处理下 下面几个数据*******/
			$data['title'] = getStr($data['title']);
			if(!empty($data['random']['types'])){
				$data['random'] = json_encode($data['random']);
			}
			
			if(!empty($data['start']['types'])){
				$data['start'] = json_encode($data['start']);
			}
			if(!empty($data['end']['types'])){
				$data['end'] = json_encode($data['end']);
			}
			
            try {
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
                $UserService = new ExaminationServiceClient(NULL);
                \ApiClient::build($UserService);
				$engprojectDo = new ExaminationRequestDTO();
				$engprojectDo->id = $examid;
				$engprojectDo->filename = $data;
    
                $result = $UserService->examEdit($engprojectDo);

                if ($result->success == TRUE) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'修改成功','code'=>'200'];
   
                    } else {
						$plaform = ['msg'=>'修改失败','code'=>'400'];
                        $plaform['data'] = [];
                    }
                } else {
					$plaform = ['msg'=>$result->message,'code'=>'400'];
                    $plaform['data'] = [];
                    
                }
            } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，修改失败','code'=>'400','data'=>[]];
            }
           
            return json_encode($plaform);
    }
	
	
	//清空回收站
    public function emptyRecycle(){
		
        $plaform = [];
		$filename['plaformid'] = $this->request->param('plaformid') ? $this->request->param('plaformid') : 1;
		$userid = $this->request->param('userid') ? $this->request->param('userid') : 0;
		if(empty($userid)){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}
		/********稍微处理下 下面几个数据*******/
		$plaform = ['msg'=>'清空成功','code'=>'200'];
            try {
                \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
                $UserService = new ExaminationServiceClient(NULL);
                \ApiClient::build($UserService);
				$engprojectDo = new ExaminationRequestDTO();
				$engprojectDo->id = $userid;
				$engprojectDo->filename = $filename;
                $result = $UserService->examEmpty($engprojectDo);

                if ($result->success == TRUE) {
                    if ($result->code == 1) {
						$plaform = ['msg'=>'修改成功','code'=>'200'];
   
                    } else {
						$plaform = ['msg'=>'修改失败','code'=>'400'];
                        $plaform['data'] = [];
                    }
                } else {
					$plaform = ['msg'=>'没有数据','code'=>'400'];
                    $plaform['data'] = [];
                    
                }
            } catch (Exception $ex) {
				$data = ['msg'=>'发生异常，修改失败','code'=>'400','data'=>[]];
            }
           
            return json_encode($plaform);
    }
	
	/**
     * 修改状态
     * @outputBuffering 
     * @param $code 
     */
    public function examStatus() 
    {
		$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		$examid = $this->request->param('examid') ? $this->request->param('examid') : 0;
        if (!$reg || !$examid || empty($this->request->param('status'))) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }

	
			/*$filename['status'] = $this->request->param('status')=='enable' ? 1 : 2;
		if($this->request->param('status')=='enable'){
		$filename['status'] = 1;
		} else if($this->request->param('status')=='end'){
			$filename['status'] = 2;
		} else if($this->request->param('status')=='disabled'){
			$filename['status'] =3;
		}*/
		$filename['status'] = (int)$this->request->param('status');
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $ExaminationService = new ExaminationServiceClient(NULL);
            \ApiClient::build($ExaminationService);
			$engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;
			$engprojectDo->field = $examid;
			$engprojectDo->username = $reg;
            $result = $ExaminationService->examStatus($engprojectDo);

            if ($result->code) {
               $data = ['msg'=>'操作成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'操作失败','code'=>'200','data'=>[]];
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }

	
	public function examDelete() 
    {
		$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		$examid = $this->request->param('examid') ? $this->request->param('examid') : '';
        if (!$reg || !$examid || empty($this->request->param('del'))) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		if( $this->request->param('del')=='deletes'){
		$filename['isdelete'] =  1;
		} else if( $this->request->param('del')=='reduction'){
			$filename['isdelete'] =  0;
		} else if( $this->request->param('del')=='removes'){
			$filename['isdelete'] =  3;
		}
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $ExaminationService = new ExaminationServiceClient(NULL);
            \ApiClient::build($ExaminationService);
			$engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;
			$engprojectDo->field = $examid;
			$engprojectDo->username = $reg;
            $result = $ExaminationService->examStatus($engprojectDo);
			if ($result->code) {
               $data = ['msg'=>'操作成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'操作失败','code'=>'200','data'=>[]];
            }
		} catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	
	//获取历史考场筛选列表
	public function histRoom() 
    {
		$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		if ($reg=='') {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $ExaminationService = new ExaminationServiceClient(NULL);
            \ApiClient::build($ExaminationService);
			$engprojectDo = new ExaminationRequestDTO();
			$engprojectDo->username = $reg;
            $result = $ExaminationService->histRoom($engprojectDo);
			if ($result->code) {
               $data = ['msg'=>'操作成功','code'=>'200','data'=>$result->data];
            } else {
               $data = ['msg'=>'操作失败','code'=>'200','data'=>[]];
            }
		} catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
    /**
     * 考场管理
     * @param  userid       int      用户id
     * @param  reg          string
     * @param  plaform_id   int      平台id
     * @param  page         int      页数
     * @param  pagesize     int      条数
     * @param  title        string      考场名称
     * @param  basic_status       int      考场状态 1进行中 2未开始 3已结束
     * @param  time         string     筛选时间
     * @param  basic_type  int     考场类型
     * @return string
     */
    public function  examManageList(){
        $plaform = [];
        $filename['adminUserId'] = $this->request->param('adminUserId') ? $this->request->param('adminUserId') : 0;
        $filename['reg'] = $this->request->param('reg') ? $this->request->param('reg') : '';
        $filename['basic_id'] = $this->request->param('basic_id') ? $this->request->param('basic_id') : '';
        $filename['plaform_id'] = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        $filename['page'] = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
        $filename['pagesize'] = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
        $filename['title'] = $this->request->param('key') ? getStr($this->request->param('key'), 'string') : '';
        $filename['plaform_title'] = $this->request->param('plaform_title') ? getStr($this->request->param('plaform_title'), 'string') : '';
        $filename['basic_status'] = $this->request->param('basic_status') ? $this->request->param('basic_status'): '';// 1进行中 2未开始 3已结束
        $filename['typesId'] = $this->request->param('basic_type')>=0 ? $this->request->param('basic_type') :'';// 1工程 0普通考场
        $time = $this->request->param('time') ? getStr($this->request->param('time'), 'string') : '';
        $filename['starttime'] = $this->request->param('startime') ? getStr($this->request->param('startime'), 'string') : '';
        $filename['endtime'] = $this->request->param('endtime') ? getStr($this->request->param('endtime'), 'string') : '';
        $data = ['msg'=>'缺少参数','code'=>'500'];

        if(!$filename['adminUserId']){
            return json_encode($data);
        }
        if ($time){
            $time = explode(' - ',$time);
            $filename['starttime'] = strtotime($time[0]);
            $filename['endtime'] = strtotime($time[1]);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;

            $result = $UserService->examManageList($engprojectDo);
	
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg'=>'查询成功','code'=>'200','count'=>json_decode($result->message)];
                    $plaform['data'] = $result->data;
//                    $plaform['list'] = json_decode($result->message,true);
                } else {
                    $plaform = ['msg'=>'查询失败','code'=>'400','count'=>0];
                    $plaform['data'] = [];
                    $plaform['code'] = 0;
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400','count'=>0];
                $plaform['data'] = [];
                $plaform['code'] = 0;
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[],'count'=>0];
            return json_encode($data);
        }
		 return json_encode($plaform);
    }


    /**
     * 删除检测记录
     * @param  adminUserId  int
     * @param  id   int      检测记录ID
     * @return string
     */
    public function deleteViolation(){
        $filename['adminUserId'] = $this->request->param('adminUserId') ? $this->request->param('adminUserId') : 0;
        $filename['id'] = $this->request->param('id') ? $this->request->param('id') : 0;//检测记录ID
        $data = ['msg'=>'缺少参数','code'=>'500'];
        if (!$filename['id'] || !$filename['adminUserId']){
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->id = $filename['id'];
            $result = $UserService->deleteViolation($engprojectDo);
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg'=>'删除成功','code'=>'200'];
//                    $plaform['list'] = json_decode($result->message,true);
                } else {
                    $plaform = ['msg'=>'删除失败','code'=>'400'];
                    $plaform['data'] = [];
                }
            } else {
                $plaform = ['msg'=>'删除失败','code'=>'400'];
                $plaform['data'] = [];

            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，删除失败','code'=>'400','data'=>[]];
            return json_encode($data);
        }

        return json_encode($plaform);
    }

    /**
     * 查看监测记录
     * @param  reg          string
     * @param  plaform_id   int      平台id
     * @param  basic_id   int      考场id
     * @param  page         int      页数
     * @param  pagesize     int      条数
     * @param  title        string      考场名称或者身份证
     * @param  basic_status       int      考场状态 1进行中 2未开始 3已结束
     * @param  detection_type     int      检测手段 1人脸识别 2操作检测
     * @return string
     */
    public function  examViolationList(){
        $plaform = [];
        $filename['adminUserId'] = $this->request->param('adminUserId') ? $this->request->param('adminUserId') : 0;
        $filename['basic_id'] = $this->request->param('basic_id') ? $this->request->param('basic_id') : 0;
        $filename['reg'] = $this->request->param('reg') ? $this->request->param('reg') : '';
        $filename['plaform_id'] = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        $filename['page'] = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
        $filename['pagesize'] = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
        $filename['title'] = $this->request->param('key') ? getStr($this->request->param('key'), 'string') : '';//考场名称
        $filename['basic_status'] = $this->request->param('basic_status') ? $this->request->param('basic_status'): '';// 1进行中 2未开始 3已结束
        $filename['detection_type'] = $this->request->param('detection_type') ? $this->request->param('detection_type'): '';// 检测手段 1人脸识别 2操作检测
        $filename['verification'] = $this->request->param('verification')>=0 ? $this->request->param('verification'): '';// 检测手段 1验证通过 0是未通过
        $filename['status'] = $this->request->param('status')>=0 ? $this->request->param('status'): '';// 1违规已处理 0违规未处理
        $filename['userName'] = $this->request->param('userName') ? $this->request->param('userName'): '';//考生姓名或者身份证
        $data = ['msg'=>'缺少参数','code'=>'500'];
        if(!$filename['adminUserId']){
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;
            $result = $UserService->examViolationList($engprojectDo);
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg'=>'查询成功','code'=>'200','count'=>json_decode($result->message)];
                    $plaform['data'] = $result->data;
//                    $plaform['list'] = json_decode($result->message,true);
                } else {
                    $plaform = ['msg'=>'查询失败','code'=>'400','count'=>0];
                    $plaform['data'] = [];
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400','count'=>0];
                $plaform['data'] = [];

            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[],'count'=>0];
            return json_encode($data);
        }

        return json_encode($plaform);
    }

    /**
     * 查看考试试卷记录
     * @param  reg          string
     * @param  plaform_id   int      平台id
     * @param  basic_id   int      考场id
     * @param  page       int      页数
     * @param  pagesize   int      条数
     * @param  title      string      考场名称或者身份证
     * @param  ispass     int      考场状态 1合格 2不合格 3未阅卷
     * @param  status     int     1未开始 2考试中 3正常 4缺考 5作弊
     * @param  terminal     int    考试终端 1手机app 2平板app 3pc端
     * @return string
     */
    public function  examPapersList(){
        $plaform = [];
        $filename['basic_id'] = $this->request->param('basic_id') ? $this->request->param('basic_id') : 0;
        $filename['page'] = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
        $filename['pagesize'] = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
        $filename['title'] = $this->request->param('key') ? getStr($this->request->param('key'), 'string') : '';//考场名称
        $filename['score'] = $this->request->param('score') ? getStr($this->request->param('score'), 'string') : '';//分数区间 60-90
        $filename['endGrade'] = $this->request->param('endGrade') ? getStr($this->request->param('endGrade'), 'string') : '';//结束分数 90
        $filename['startGrade'] = $this->request->param('startGrade') ? getStr($this->request->param('startGrade'), 'string') : '';// 开始分数 60
        $filename['type'] = $this->request->param('type') ? $this->request->param('type'): '';// 考场状态 1正常 2异常
        $filename['ispass'] = $this->request->param('ispass') ? $this->request->param('ispass'): '';// 考场状态 1合格 2不合格 3未阅卷
        $filename['status'] = $this->request->param('status') ? $this->request->param('status'): '';// // 1未开始 2考试中 3正常 4缺考 5作弊
        $filename['terminal'] = $this->request->param('terminal') ? $this->request->param('terminal'): '';// 考试终端 1手机app 2平板app 3pc端
        $filename['userName'] = $this->request->param('userName') ? $this->request->param('userName'): '';//考生姓名或者身份证
        $data = ['msg'=>'缺少参数','code'=>'500'];

        if(!$filename['basic_id']){
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;
            $result = $UserService->getExamPapersList($engprojectDo);

            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg'=>'查询成功','code'=>'200','count'=>json_decode($result->message?$result->message:0)];
                    $plaform['data'] = $result->data;
//                    $plaform['list'] = json_decode($result->message,true);
                } else {
                    $plaform = ['msg'=>'查询失败','code'=>'400','count'=>0];
                    $plaform['data'] = [];
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400','count'=>0];
                $plaform['data'] = [];

            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[],'count'=>0];
            return json_encode($data);
        }

        return json_encode($plaform);
    }

    //交卷
    public function score(){
        $paper_id = $this->request->param('paper_id') ? $this->request->param('paper_id/d') : 0;
        $basicid = $this->request->param('basicid') ? $this->request->param('basicid/d') : 0;
        $answer = $this->request->param('answer/a') ? $this->request->param('answer/a') : [];
//        $answer = $this->request->param('answer') ? $this->request->param('answer') : [];//每道题得分 ['458'=>'BCD','56589'=>['asfasgasgag',1]] 56589是填空题 asfasgasgag是答案 1是正确 0是错误
//        $answer = ['45811'=>'BCD','65635'=>'B','65622'=>'A','56589'=>['asfasgasgag',1]];
        if(!$paper_id  || $answer=='' ){
            $data = ['msg'=>'缺少参数，阅卷失败','code'=>'500','data'=>[]];
            return json_encode($data);
        }

        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new ExaminationServiceClient(NULL);
            \ApiClient::build($api);
            $Examination = new ExaminationRequestDTO();
            $Examination->filename['answer'] = json_encode($answer);
            $Examination->filename['paper_id'] = $paper_id;
            $Examination->filename['basicid'] = $basicid;
            $result = $api->carryOut($Examination);
            if ($result->code==1){
                $data =  ['msg'=>'提交成功','code'=>'200','data'=>[]];
            }else{
                $data = ['msg'=>'提交失败','code'=>'400','data'=>json_encode($answer)];
            }

        } catch (Exception $ex) {
            $data = ['msg'=>'提交失败','code'=>'400','data'=>json_encode($answer)];
        }
        return json_encode($data);
    }

    //添加检测记录
    public function addViolation(){
        $paper_id = $this->request->param('paper_id') ? $this->request->param('paper_id/d') : 0;
        $plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : 0;
        $gdl_userid = $this->request->param('gdl_userid') ? $this->request->param('gdl_userid/d') : 0;
        $userid = $this->request->param('userid') ? $this->request->param('userid/d') : 0;
        $basicid = $this->request->param('basicid') ? $this->request->param('basicid/d') : 0;
        $username = $this->request->param('username') ? $this->request->param('username') : '';
        $identity_id = $this->request->param('identity_id') ? $this->request->param('identity_id/d') : 0;
        $rule = $this->request->param('rule') ? $this->request->param('rule') : 'random';//规则 random(考试中),start(考试后),end(考试结束)
        $type = $this->request->param('type') ? $this->request->param('type/d') : 1;//检查手段 1人脸 2是操作

        if(!$identity_id || !$plaform_id){
            $data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
            return json_encode($data);
        }
        \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
        //获取用户的信息
        $AdminUserServiceClient = new AdminUserServiceClient(NULL);
        $ExaminationService = new ExaminationServiceClient(NULL);
        \ApiClient::build($AdminUserServiceClient);
        \ApiClient::build($ExaminationService);
        $UserDTO = new UserDTO();
        $ExaminationRequestDTO = new ExaminationRequestDTO();
        $ExaminationRequestDTO_a = new ExaminationRequestDTO();
        $ExamsessionModel = new Examsession();
        $UserDTO->id = $plaform_id;
        $data = [
            'userid'=>$userid,
            'gdl_userid'=>$gdl_userid,
            'id'=>$identity_id# company_user id
        ];
        $UserDTO->data = $data;

        $userInfo =  $AdminUserServiceClient->userInfo($UserDTO);
        $userInfo = $userInfo->code==200?$userInfo->data[0]:[];

        if(!$userInfo){
            $data = ['msg'=>'用户不存在，失败！','code'=>'400','data'=>[]];
            return json_encode($data);
        }
        $basic_info = Db::name('basic')->where(['id' => $basicid])->field("id,basic")->find();
        session_start();
        if ($type==1){//人脸检测
            $remark = "";
            $faceImgA = "";
            $faceImgB = "";
            $faceSdk = strtolower('youtu');
            $faceType = 2;
            if(!$_FILES['file']['name']){//验证照片抓取失败
				$monitorInfo = [
					'identity_id' => $identity_id,
					'truename' => $userInfo['truename']?$userInfo['truename']:"",
					'userName' => $userInfo['username']?$userInfo['username']:"",
					'basic' => $basic_info?$basic_info['basic']:'',
					'userIdcard' => $userInfo['idcard'],
					'current_img' => $address,
					'source_img' => $userInfo['photoCollect'], //留底照片
					'instructions' => "验证照片抓取失败！",
					'type' => $type,
					'rule' => $rule,
					'basicId' => $basicid,
					'startTime' => date('Y-m-d H:i:s',time()),
				];
				$monitorInfo['reason'] ="验证照片抓取失败！" ;
				$monitorInfo['verification'] = 0;
				$ExaminationRequestDTO_a->filename = $monitorInfo;
				//$ExamsessionModel->modifyExamSession(['suspicion' => 2], session_id());
				$ExamsessionModel->where(['identity_id'=>$identity_id,'basicid'=>$basicid])->update(['suspicion' => 2]);
				$data = $ExaminationService->addViolation($ExaminationRequestDTO_a);
				return json_encode(['code' => 200, 'massage' => "提交违规操作成功！",'data' =>['succ' => 0]]);																											
				
               // $data = ['msg'=>'检测照片没有上传，失败！','code'=>'400','data'=>[]];
               // return json_encode($data);
            }else{
				$result = \Qiniu::instance()->upload(); //七牛上传
				$address = $result[0]['key'];
				$address = Config::get('qiniu.QINIU_DOMAIN') . $address;
	//            $souce_image = file_get_contents($_FILES['file']['tmp_name']);
				//暂时传递URL图片
	//            if ($faceType == 2) {
	//                $faceImgA = base64_encode(file_get_contents($_FILES['file']['tmp_name']));
	//            } else {
	//                $faceImgA = createLocalFile($address, '../upload/facetemp/', in_array($faceSdk, array('youtu')));
	//            }
				try {
	              // $photo_collect = Db::name('user_company')->where(['id' => $identity_id])->field("userId,photoCollect,vface")->find();


					//暂时传递URL图片
	//                if ($userInfo['vface'] == 2 && !empty($userInfo['photoCollect'])) {
	//                    if ($faceType == 2) {
	//                        $faceImgB = base64_encode(file_get_contents($userInfo['photoCollect']));
	////                $faceImgB = $photo_collect['photoCollect']; //如果优图才启用 URL
	//                    } else {
	//                        $faceImgB = createLocalFile($userInfo['photoCollect'], '../upload/facetemp/', in_array($faceSdk, array('youtu'))); //获取图片内容
	//                    }
	//                }
					$ExaminationRequestDTO->name = $address;
					$ExaminationRequestDTO->field = $userInfo['photoCollect'];
					$ExaminationRequestDTO->type = $faceType;
					$faceMessage = Config::get('message.face');
					$similarity = 0;
					$judgeResult = -1;
					//比对的两张照片同时不为空，才可以调用比对接口
					//暂时传递URL图片
	//                if (!empty($faceImgA) && !empty($faceImgB)) {
                    if ($userInfo['vface'] == 2) {
                         if (!empty($address) && !empty($userInfo['photoCollect'])) {
                            $remark = '人脸有异常！';
                            $result = $ExaminationService->identify($ExaminationRequestDTO);
                            $similarity = $result->data[0]['similarity'];
                            $judgeResult = $faceSdk == 'facevisa' ? $result->data[0]['result'] : $result->data[0]['errorcode'];
                        } else {
                            $remark = '留底照片未上传/未通过！';
                            $similarity = 0;
                        }
                    }else{
                        $remark = '留底照片未上传/未通过！';
                        $similarity = 0;
                    }
					
					$monitorInfo = [
						'identity_id' => $identity_id,
						'truename' => $userInfo['truename']?$userInfo['truename']:"",
						'userName' => $userInfo['username']?$userInfo['username']:"",
						'basic' => $basic_info?$basic_info['basic']:'',
						'current_img' => $address,
						'source_img' => $userInfo['photoCollect'], //留底照片
						'userIdcard' => $userInfo['idcard'],
						'similarity' => $similarity,
						'judge_result' => $judgeResult,
						'face_sdk' => $faceSdk,
						'instructions' => $remark,
						'type' => $type,
						'rule' => $rule,
						'basicId' => $basicid,
						'startTime' => date('Y-m-d H:i:s',time()),
					];
					if ($similarity >= FaceType::PASS) {
						$monitorInfo['verification'] = 1;
						$monitorInfo['reason'] = $faceMessage[FaceType::message1];
						$monitorInfo['instructions'] = "----";
						$ExaminationRequestDTO_a->filename = $monitorInfo;
						//$ExamsessionModel->modifyExamSession(['suspicion' => 1], session_id());
						$data = $ExaminationService->addViolation($ExaminationRequestDTO_a);
	//                    $id = $data->code==1?$data->message:0;
	//                    $msg = [
	//                        'id' => $id,
	//                        'image' => base64_encode($souce_image)
	//                    ];
	//                    $host_config = Config::get('rabbitmq.config');
	//                    $upload = Config::get('rabbitmq.upload');
	//                    $rabbitMq = new \RabbitMq($host_config, $upload['exchange_name'], $upload['queue_name'], $upload['routing_key']);
	//                    $rabbitMq->send($msg);

						return json_encode(['code' => 200, 'massage' => $faceMessage[FaceType::message1],'data' =>['succ' => 1]]);
					} else {
						$monitorInfo['reason'] = $faceMessage[FaceType::message2];
						$monitorInfo['verification'] = 0;
						$monitorInfo['instructions'] = $remark;
						$ExaminationRequestDTO_a->filename = $monitorInfo;
						//$ExamsessionModel->modifyExamSession(['suspicion' => 2], session_id());
						$ExamsessionModel->where(['identity_id'=>$identity_id,'basicid'=>$basicid])->update(['suspicion' => 2]);
						$data = $ExaminationService->addViolation($ExaminationRequestDTO_a);
	//                    $id = $data->code==1?$data->message:0;
	//                    $msg = [
	//                        'id' => $id,
	//                        'image' => base64_encode($souce_image)
	//                    ];
	//                    $host_config = Config::get('rabbitmq.config');
	//                    $upload = Config::get('rabbitmq.upload');
	//                    $rabbitMq = new \RabbitMq($host_config, $upload['exchange_name'], $upload['queue_name'], $upload['routing_key']);
	//                    $rabbitMq->send($msg);
						return json_encode(['code' => 200, 'massage' => $faceMessage[FaceType::message2],'data' =>['succ' => 0]]);
					}
				} catch (Exception $ex) {
					return json_encode(['msg' => '失败', 'code' => '400']);
				}
			}
            
        }else{//操作检测
            $monitorInfo = [
                'identity_id' => $identity_id,
                'truename' => $userInfo['truename']?$userInfo['truename']:"",
                'userName' => $userInfo['username']?$userInfo['username']:"",
                'basic' => $basic_info?$basic_info['basic']:'',
                'userIdcard' => $userInfo['idcard'],
                'instructions' => "有违规操作,返回退出APP多次！",
                'type' => $type,
                'rule' => $rule,
                'basicId' => $basicid,
                'startTime' => date('Y-m-d H:i:s',time()),
            ];
            $monitorInfo['reason'] ="有违规操作,返回退出APP多次！" ;
            $monitorInfo['verification'] = 0;
            $ExaminationRequestDTO_a->filename = $monitorInfo;
           // $ExamsessionModel->modifyExamSession(['suspicion' => 2], session_id());
		   $ExamsessionModel->where(['identity_id'=>$identity_id,'basicid'=>$basicid])->update(['illegalbehavior' => 2]);
            $data = $ExaminationService->addViolation($ExaminationRequestDTO_a);
            return json_encode(['code' => 200, 'massage' => "提交违规操作成功！",'data' =>['succ' => 1]]);
        }

//        return json_encode($data);
    }

    //公布考生成绩
    public function publishUserScore(){
        $basicid = $this->request->param('basicid') ? $this->request->param('basicid/d') : 0;
        if(!$basicid){
            $data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
            return json_encode($data);
        }

        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new ExaminationServiceClient(NULL);
            \ApiClient::build($api);
            $Examination = new ExaminationRequestDTO();
            $Examination->filename['basicid'] = $basicid;
            $result = $api->publishUserScore($Examination);
            if ($result->code==1){
                $data =  ['msg'=>'公布成功','code'=>'200','data'=>[]];
            }else{
                $data = ['msg'=>$result->message?$result->message:"公布失败",'code'=>'400','data'=>[]];
            }

        } catch (Exception $ex) {
            $data = ['msg'=>'公布失败','code'=>'500','data'=>[]];
        }
        return json_encode($data);
    }

    /**
     *test_paper 用户个人试卷
     */
    public function readPaper(){
        $id = $this->request->param('id');
        $eid = $this->request->param('eid');
        $identity_id = $this->request->param('identity_id');
        if ($eid==0 || !$identity_id){
            return json_encode(['code'=>400,"msg"=>"缺少参数","data"=>[]]);
        }
        if ($id){
            $arg = ['basic_id'=>$id,'identity_id'=>$identity_id,'id'=>$eid];
        }else{
            $arg = ['identity_id'=>$identity_id,'id'=>$eid];
        }
        /***获取用户试卷 答题情况**/
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new AdminpaperServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new AdminpaperDTO();
            $engprojectDo->id = $eid;
            $engprojectDo->plaform_id = $identity_id;
            $result = $api->lookExamsPaper($engprojectDo);
            $data = json_decode(strip_tags($result->message),true);

            $result = ['code'=>200,"msg"=>"成功","data"=>$data];
        } catch (Exception $ex) {
            $result = ['code'=>400,"msg"=>"成功","data"=>[]];
        }
        return json_encode($result);
    }

	
	//导出考场列表
	public function downExcel(){
        $plaform = [];
        $filename['reg'] = $this->request->param('reg') ? $this->request->param('reg') : '';
		$filename['id'] = $this->request->param('id') ? $this->request->param('id') : '';
        $filename['page'] = $this->request->param('page') > 1 ? $this->request->param('page/d') : 1;
        $filename['pagesize'] = $this->request->param('pagesize') > 0 ? $this->request->param('pagesize/d') : 10;
        $filename['title'] = $this->request->param('key') ? getStr($this->request->param('key'), 'string') : '';
        $filename['status'] = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';
        $filename['del'] = $this->request->param('del') ? getStr($this->request->param('del'), 'string') : '';
        /*         * *********** */
        $filename['monitorRule'] = $this->request->param('monitorRule') ? $this->request->param('monitorRule/d') : 0;
        $filename['isexam'] = $this->request->param('isexam') ? getStr($this->request->param('isexam'), 'string') : '';
        $filename['exam'] = $this->request->param('exam') ? getStr($this->request->param('exam'), 'string') : '';
        $filename['endtime'] = $this->request->param('endtime') ? $this->request->param('endtime') : '';
        $filename['startime'] = $this->request->param('startime') ? $this->request->param('startime') : '';
		$filename['down'] = 'excels';
        /*         * *********** */
        if(empty($filename['reg'])){
		
					$data = ['msg'=>'缺少参数','code'=>'500'];
					return json_encode($data);
		}
		
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk', 'gdlAgkSdk'));
            $api = new ExaminationServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->filename = $filename;
            $result = $api->examList($engprojectDo);

            if ($result->success == TRUE) {
                if ($result->code == 1) {
                     $index= $result->data;
                } else {
                    $index=[];
                }
            } else {
                $index=[];
            }
        } catch (Exception $ex) {
         $index=[];
        }

		
		
		$filename = '考场列表'.date('YmdHis');  
		$header = array('排序','考场名称','试卷来源题库','绑定试卷名称','考试起止时间','考试类型','监管规则','启用状态','所属平台');  
		
		createtable($filename,$header,$index);  
		
    }
	
	
    /**
     * 预览试卷
     * @return string
     */
    public function readUserpaper(){
        $id = $this->request->param('id');
        $eid = $this->request->param('eid');//试卷ID
        $identity_id = $this->request->param('identity_id');//身份ID
        if ($eid==0){
            return "缺少参数ID";
        }
        if ($id){
            $arg = ['basic_id'=>$id,'identity_id'=>$identity_id,'id'=>$eid];
        }else{
            $arg = ['identity_id'=>$identity_id,'id'=>$eid];
        }
        /***获取用户试卷 答题情况**/
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new AdminpaperServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new AdminpaperDTO();
            $engprojectDo->id = $eid;
            $result = $api->lookExamsPaper($engprojectDo);
            $data = json_decode($result->message,true);
        } catch (Exception $ex) {
            $data = ['list'=>[],'count'=>0,'qbankName'=>'','duration'=>'','totalScore'=>'','passScore'=>'','paperName'=>''];
        }
        /*********************/
        vendor("TCPDF.tcpdf");
        $num=[
            '一',
            '二',
            '三',
            '四',
            '五',
            '六',
        ];
        $ques_type = ['一、单选题'=>'单选题','二、多选题'=>'多选题','三、判断题'=>'判断题','四、填空题'=>'填空题','五、主观题'=>'主观题'];



        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle($data['paperName']);
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
        // 设置页眉和页脚信息
        $txt = $data['paperName'];
        $pdf->SetHeaderData(false, 20, false, $txt,array(0,64,255), array(0,64,128)); //第一个参数是放log的
        // 设置页眉和页脚字体
        $pdf->setHeaderFont(Array('stsongstdlight', '', '10'));

        // ---------------------------------------------------------

        //Close and output PDF document
        // remove default header/footer
        $pdf->setPrintHeader(true);
        $pdf->setPrintFooter(false);

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set some language-dependent strings (optional)
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        $pdf->SetFont('times', 'BI', 10);
        $pdf->AddPage();
        $pdf->SetFont('stsongstdlight', '', 14);
        $txt = $data['paperName'];
        $pdf->Write(0, $txt, '', 0, 'C', true, 0, false, false, 0);
        $ic=0;
        $pdf->SetFont('stsongstdlight', '', 10);
        $html = '
				<table border="0">
					<tr>
						<th>来源题库：'.$data['qbankName'].'</th>
						
						<th align="right">考试时长：'.$data['duration'].'</th>
					</tr>
					<tr>
						<th>试题数目：'.$data['count'].'</th>
						
						<th align="right">及格分数：'.$data['passScore'].'</th>
					</tr>
					
				</table>';
//        $nums = ['1'=>'0','2'=>'0','3'=>'0','4'=>'0','5'=>'0'];
//        $nums = ['一、单选题'=>0,'二、多选题'=>0,'三、判断题'=>0,'四、填空题'=>0,'五、主观题'=>0];
//
//        foreach($data['list'] as $kl=>$vl){
//            $nums[$kl] = count($vl);
//        }
        $html .= '
				<table border="1">
					<tr align="center">
						<th>单选题</th>
						<th>多选题</th>
						<th>判断题</th>
						<th>填空题</th>
						<th>问答题</th>
						<th>总分</th>
					</tr>
					<tr align="center">
					<td>'.$data['sure_score_types'][1].'</td>
					<td>'.$data['sure_score_types'][2].'</td>
					<td>'.$data['sure_score_types'][3].'</td>
					<td>'.$data['sure_score_types'][4].'</td>
					<td>'.$data['sure_score_types'][5].'</td>
					<td>'.$data['sure_score_types']['total'].'</td>
					</tr>
					
				</table>';

        $html .= '<div style="width:70px;height:30px;"></div>
				<div   style="border:solid 1px #CCC;">
				<table border="0" >
				    <tr align="center">
						<th ></th>
						
						<th ></th>
					</tr>
					<tr align="center">
						<th align="left">&nbsp;&nbsp;&nbsp;&nbsp;考生姓名：'.$data['userinfo']['usertruename'].'</th>
						
						<th  align="left">身份证号：'.$data['userinfo']['idcard'].'</th>
					</tr>
					<tr align="center">
						<th align="left">&nbsp;&nbsp;&nbsp;&nbsp;考试时间：'.$data['starttime'].'</th>
						
						<th  align="left">考试耗时：'.$data['starttime'].'</th>
					</tr>
					<tr align="center">
						<th align="left">&nbsp;&nbsp;&nbsp;&nbsp;考试说明：'.$data['remark'].'</th>
						
						<th  align="left">身份验证：'.$data['type'].'</th>
					</tr>
					<tr align="center">
						<th align="left">&nbsp;&nbsp;&nbsp;&nbsp;考试得分：'.$data['modified'].'</th>
						
						<th  align="left">考试结果：'.$data['ispass'].'</th>
					</tr>
					
				</table>
				<div></div>
				<div style="float:left;padding-left:50px">
				    <table border="1"  width="600">
					<tr align="center">
						<th>单选题</th>
						<th>多选题</th>
						<th>判断题</th>
						<th>填空题</th>
						<th>问答题</th>
						<th>总分</th>
					</tr>
					<tr align="center">
					<td>'.$data['questype'][1].'</td>
					<td>'.$data['questype'][2].'</td>
					<td>'.$data['questype'][3].'</td>
					<td>'.$data['questype'][4].'</td>
					<td>'.$data['questype'][5].'</td>
					<td>'.$data['questype']['total'].'</td>
					</tr>
				</table>
				</div>
                
</div>';
        $pdf->writeHTML($html, true, false, true, false, '');
        foreach($data['list'] as $ko=>$vo){
            if (!empty($vo)){
                $pdf->SetFont('stsongstdlight', '', 12);
                $txt = $num[$ic].'、'.$ques_type[$ko];
                $pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);

                $txt = '';
                $pdf->SetFont('stsongstdlight', '', 10);
                $i=1;

                foreach($vo as $kl=>$vl){
                    $txt .= $i.'、'.$vl["question"]."\r\n".str_replace(array("\r\n","\n",'\r'),"  ",$vl["select"])."\r\n考生答案：".$vl["useranswer"]."\r\n正确答案：".$vl["answer"]."\r\n本题得分：".$vl["userscore"]."\r\n\r\n";//."\r\n正确答案：".$vl["q_answer"]
                    $i++;
                }
                //$txt = htmlspecialchars_decode($txt);
                $txt = str_replace(array('&lt;p&gt;','&lt;/p&gt;'),'',$txt);//处理掉p 标签
                $pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
                $ic++;
            }
        }
        $pdf->Output('kaoshi.pdf', 'I');
        exit;
    }

    /**
     * 让用户立即交卷
     * @param  reg          string
     * @param  plaform_id   int      平台id
     * @param  basic_id   int      考场id
     * @param  page         int      页数
     * @param  pagesize     int      条数
     * @param  title        string      考场名称或者身份证
     * @param  basic_status       int      考场状态 1进行中 2未开始 3已结束
     * @param  detection_type     int      检测手段 1人脸识别 2操作检测
     * @return string
     */
    public function  examCloseMake(){
        $plaform = [];
        $violation_id = $this->request->param('violation_id') ? $this->request->param('violation_id') : 0;//监测记录id
        $basic_id = $this->request->param('basic_id') ? $this->request->param('basic_id') : 0;//basic_id 考场ID
        $data = ['msg'=>'缺少参数','code'=>'500'];

        if(!$violation_id){
            return json_encode($data);
        }
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $engprojectDo->id = $violation_id;
            $engprojectDo->eveid = $basic_id;
            $result = $UserService->examCloseMake($engprojectDo);
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $plaform = ['msg'=>'交卷成功','code'=>'200'];
//                    $plaform['data'] = $result->data;
//                    $plaform['list'] = json_decode($result->message,true);
                } else {
                    $plaform = ['msg'=>$result->message,'code'=>'400'];
//                    $plaform['data'] = [];
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400'];
                $plaform['data'] = [];

            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
            return json_encode($data);
        }

        return json_encode($plaform);
    }

    /* 导出考场管理列表 */
    public function downloadManageList()
    {
        $filename['adminUserId'] = $this->request->param('adminUserId') ? $this->request->param('adminUserId') : 0;
        $filename['basic_id'] = $this->request->param('basic_id') ? $this->request->param('basic_id') : 0;//逗号间隔的考场id
        $filename['reg'] = $this->request->param('reg') ? $this->request->param('reg') : '';
        $filename['plaform_id'] = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        $data = ['msg'=>'缺少参数','code'=>'500'];
        if(!$filename['adminUserId']){
            return json_encode($data);
        }
        $header = [ 'ID', '考场名称', '考试起止时间','考场状态','应参考人数','已参考人数','未参考人数','合格人数','合格率','所属平台'];
        $arr_data = array();
        $time = time();
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $filename['page'] = 1;
            $filename['pagesize'] = 999999;
            $engprojectDo->filename = $filename;
            $result = $UserService->examManageList($engprojectDo);
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $data = $result->data;
                    foreach ($data as $key=>$value){
                        $arr_data[$value['id']]['ID'] = $value['id'];
                        $arr_data[$value['id']]['basic'] = $value['basic'];
                        $arr_data[$value['id']]['basic_time'] = $value['basic_time'];
                        $arr_data[$value['id']]['timeRemaining'] = $value['timeRemaining'];
                        $arr_data[$value['id']]['users_should_nums'] = $value['users_should_nums'];
                        $arr_data[$value['id']]['users_ever_nums'] = $value['users_ever_nums'];
                        $arr_data[$value['id']]['users_not_nums'] = $value['users_not_nums'];
                        $arr_data[$value['id']]['users_pass_nums'] = 0;
                        $arr_data[$value['id']]['users_pass'] = "0%";
                        $arr_data[$value['id']]['plaform_name'] = $value['plaform_name'];
                    }
                    array_multisort(array_column($arr_data,'ID'),SORT_DESC,$arr_data);
                } else {
                    $plaform = ['msg'=>'查询失败','code'=>'400'];
                    $plaform['data'] = [];
                    return json_encode($plaform);
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400'];
                $plaform['data'] = [];
                return json_encode($plaform);
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
            return json_encode($data);
        }
        ob_clean();
        if ($error = \Excel::export($header, $arr_data, "考场管理实时数据表", '2007')) {
            throw new Exception($error);
        }
    }

    /* 导出监测记录列表 */
    public function downloadViolationList()
    {
        $filename['adminUserId'] = $this->request->param('adminUserId') ? $this->request->param('adminUserId') : 0;
        $filename['violation_id'] = $this->request->param('violation_id') ? $this->request->param('violation_id') : 0;//逗号间隔的监测记录id
        $filename['basic_id'] = $this->request->param('basic_id') ? $this->request->param('basic_id') : 0;//考场id
        $filename['reg'] = $this->request->param('reg') ? $this->request->param('reg') : '';
        $filename['plaform_id'] = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        $data = ['msg'=>'缺少参数','code'=>'500'];
        if(!$filename['adminUserId']){
            return json_encode($data);
        }
        $header = [ 'ID', '考场名称', '考场状态','考生信息','监测手段','监测时间','验证状态','留底照片','抓取照片','违规说明'];
        $arr_data = array();
        $time = time();
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $filename['page'] = 1;
            $filename['pagesize'] = 999999;
            $engprojectDo->filename = $filename;
            $result = $UserService->examViolationList($engprojectDo);
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $data = $result->data;
                    foreach ($data as $key=>$value){
                        $arr_data[$value['id']]['ID'] = $value['id'];
                        $arr_data[$value['id']]['basic'] = $value['basic'];
                        $arr_data[$value['id']]['basic_status'] = $value['basic_status'];
                        $arr_data[$value['id']]['userinfo'] = $value['userName']."({$value['userIdcard']})";
                        $arr_data[$value['id']]['type'] = $value['type'];
                        $arr_data[$value['id']]['violation_time'] = $value['violation_time'];
                        $arr_data[$value['id']]['verification'] = $value['verification'];
                        $arr_data[$value['id']]['current_img'] = $value['current_img'];
                        $arr_data[$value['id']]['source_img'] = $value['source_img'];
                        $arr_data[$value['id']]['instructions'] = $value['instructions'];
                    }
                    array_multisort(array_column($arr_data,'ID'),SORT_DESC,$arr_data);
                } else {
                    $plaform = ['msg'=>'查询失败','code'=>'400'];
                    $plaform['data'] = [];
                    return json_encode($plaform);
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400'];
                $plaform['data'] = [];
                return json_encode($plaform);
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
            return json_encode($data);
        }
        ob_clean();
        if ($error = \Excel::export($header, $arr_data, "考生监测记录实时数据表", '2007')) {
            throw new Exception($error);
        }
    }

    /* 导出考试试卷列表 */
    public function downloadPapersList()
    {
        $filename['violation_id'] = $this->request->param('violation_id') ? $this->request->param('violation_id') : 0;//逗号间隔的监测记录id
        $filename['basic_id'] = $this->request->param('basic_id') ? $this->request->param('basic_id') : 0;//考场id
        $data = ['msg'=>'缺少参数','code'=>'500'];
        if(!$filename['basic_id']){
            return json_encode($data);
        }
        $header = [ 'ID', "真实姓名","身份证号","绑定手机","考试状态","开始考试时间","是否异常","考试分数","是否合格","考试耗时","考试说明","考试终端"];
        $arr_data = array();
        $time = time();
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlAgkSdk'));
            $UserService = new ExaminationServiceClient(NULL);
            \ApiClient::build($UserService);
            $engprojectDo = new ExaminationRequestDTO();
            $filename['page'] = 1;
            $filename['pagesize'] = 999999;
            $engprojectDo->filename = $filename;
			$engprojectDo->type = 1;//  1：身份证不隐藏
            $result = $UserService->getExamPapersList($engprojectDo);
            if ($result->success == TRUE) {
                if ($result->code == 1) {
                    $data = $result->data;
                    foreach ($data as $key=>$value){
                        $arr_data[$value['identity_id']]['ID'] = $value['identity_id'];
                        $arr_data[$value['identity_id']]['usertruename'] = $value['usertruename'];
                        $arr_data[$value['identity_id']]['idcard'] = $value['idcard'];
                        $arr_data[$value['identity_id']]['phone'] = $value['phone'];
                        $arr_data[$value['identity_id']]['basic_status'] = $value['basic_status'];
                        $arr_data[$value['identity_id']]['basic_start_time'] = $value['basic_start_time'];
                        $arr_data[$value['identity_id']]['basic_type'] = $value['basic_type'];
                        $arr_data[$value['identity_id']]['score'] = $value['score'];
                        $arr_data[$value['identity_id']]['ispass'] = $value['ispass'];
                        $arr_data[$value['identity_id']]['time'] = $value['time'];
                        $arr_data[$value['identity_id']]['remark'] = $value['remark'];
                        $arr_data[$value['identity_id']]['terminal'] = $value['terminal'];
                    }
                    array_multisort(array_column($arr_data,'ID'),SORT_DESC,$arr_data);
                } else {
                    $plaform = ['msg'=>'查询失败','code'=>'400'];
                    $plaform['data'] = [];
                    return json_encode($plaform);
                }
            } else {
                $plaform = ['msg'=>'没有数据','code'=>'400'];
                $plaform['data'] = [];
                return json_encode($plaform);
            }
        } catch (Exception $ex) {
            $data = ['msg'=>'发生异常，查询失败','code'=>'400','data'=>[]];
            return json_encode($data);
        }

//                var_dump($arr_data);die;
        ob_clean();
        if ($error = \Excel::export($header, $arr_data, "考生成绩实时数据表", '2007')) {
            throw new Exception($error);
        }
    }
}
